package com.blb.servlet;

import com.blb.pojo.Result;
import com.blb.servlet.BaseServlet;
import com.blb.utils.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Collection;
import java.util.UUID;

@MultipartConfig
@WebServlet("/file/*")
public class FileServlet extends BaseServlet {

    /**
     * a.jpg,b.jpg
     * 1111.jpg,2222.jpg,
     *
     * 文件上传
     * @param req
     * @param resp
     * @throws UnsupportedEncodingException
     */
    public void upload(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.setCharacterEncoding("utf8");
        Collection<Part> parts = req.getParts();
        StringBuffer stringBuffer = new StringBuffer();

        for (Part part : parts) {
            //获取上传的文件名
            String fileName = part.getSubmittedFileName();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString() + suffix;
            stringBuffer.append(newFileName+",");

            //2.构建I流对象和O流对象
            InputStream in = part.getInputStream();
            FileOutputStream out = new FileOutputStream("G:\\JAVA_project\\xrtqhText\\"+newFileName);

            //3.IO读写
            IOUtils.readWrite(in, out);
        }

        String fileNames = stringBuffer.toString();
        fileNames = fileNames.substring(0, fileNames.length()-1);

        //写回消息
        resp.getWriter().write(Result.ok(fileNames));
    }

    /**
     * 显示图像
     * @param req
     * @param resp
     */
    public void show(HttpServletRequest req, HttpServletResponse resp){
        String name = req.getParameter("name");
        try {
            resp.setContentType("image/jpeg");
            FileInputStream in = new FileInputStream("G:\\JAVA_project\\xrtqhText\\" + name);
            ServletOutputStream out = resp.getOutputStream();
            IOUtils.readWrite(in, out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
